export const isObject = (val) => Object.prototype.toString.call(val) === '[object Object]'
export const isEmpty = (s, invalid) => {
    if (s === '' || s === undefined || s === null || invalid?.includes(s)) {
        return false
    }
    return true
}
export const valueToObject = (obj) => {
    if (isObject(obj)) {
        return obj
    }
    return {}
}

export const valueToArray = (arr) => {
    if (Array.isArray(arr)) {
        return arr
    }
    return []
}

export function isWxBrowser(ua: string) {
    return /MicroMessenger/i.test(ua)
}

export function isMobile(ua: string) {
    return /(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i.test(ua)
}

export function isIOS(ua: string) {
    return /iPhone|iPad|iPod/i.test(ua)
}

export function isAndroid(ua: string) {
    return /Android/i.test(ua)
}
let index = 1000
export const getUid = (key: string): string | number => {
    return key ? `${key}_${index++}` : index++
}

export const loadJs = (url: string) => new Promise((resolve, reject) => {
    const el = document.createElement('script')
    el.src = url
    el.onload = resolve
    el.onerror = reject
    const s = document.getElementsByTagName('script')[0] as HTMLScriptElement
    s.parentNode!.insertBefore(el, s)
})

// 邮箱脱敏处理
export function noPassByEmail(email: string) {
    if (!email) return ''
    let new_email = email
    if (String(email).indexOf('@') > 0) {
        let str = email.split('@')
        let _s = ''
        if (str[0].length > 3) { // @前面多于3位
            for (let i = 3; i < str[0].length; i++) {
                _s += '*'
            }
            new_email = str[0].substr(0, 3) + _s + '@' + str[1]
        } else { // @前面小于等于于3位
            for (let i = 1; i < str[0].length; i++) {
                _s += '*'
            }
            new_email = str[0].substr(0, 1) + _s + '@' + str[1]
        }
    }
    return new_email
}

/**
 * 指定位置插入字符串
 * @param {string} str
 * @param {number} index
 * @param {string} char
 * @returns
 */
export const assignCharByIndex = (str, index = 6, char = '\n') => {
    if (!str || typeof str !== 'string') {
        return ''
    }
    const strLen = str.length
    if (strLen < index) {
        return str
    }
    const a = str.split('')
    let b = index
    while (b < strLen) {
        a.splice(b, 0, char)
        b += index
    }
    return a.join('')
}


export const clipHTML = (value: string) => {
    if (!value) {
        return ''
    }
    const reg = /(\s+style="[^"]*")|(\s+class="[^"]*")|(&nbsp;)/gi
    // const reg2 = /<([a-z0-9]+?)(?:\s+?[^>]*?)?>\s*?<\/\1>/gi
    let html = value.replace(reg, '')
    // html = html.replace(reg2, '').replace(reg2, '')
    html = html.replace(/↵/gi, '')
    html = html.replace(/&middot;/ig, '·')
    html = html.replace(/&amp;/ig, '&')
    html = html.replace(/&ldquo;/ig, '“')
    html = html.replace(/&rdquo;/ig, '”')
    html = html.replace(/&rsquo;/ig, '’')
    html = html.replace(/<a/ig, '<a target="_blank" ')
    return html
}

export const openPopupWindow = (url = '', width = 700, height = 500) => {
    const left = (screen.width / 2) - (width / 2);
    const top = (screen.height / 2) - (height / 2);
    const opts = {
        toolbar: 'no',
        location: 'no',
        directories: 'no',
        status: 'no',
        menubar: 'no',
        scrollbars: 'no',
        resizable: 'no',
        copyhistory: 'no',
        width,
        height,
        top,
        left
    }
    const param = Object.keys(opts).reduce((acc: string[], key) => {
        acc.push(`${key}=${opts[key]}`)
        return acc
    }, []).join(',')
    const wind = window.open(url, 'popupWindow', param);
    const closeWind = (delay = 0) => {
        try {
            if (delay) {
                setTimeout(() => {
                    wind?.close()
                }, delay)
            } else {
                wind?.close()
            }
        } catch (error) {
            // console.log('closeWind error', error)
        }
    }
    return {
        wind,
        closeWind,
    }
}

export const sleepSync = async (delay = 300) => {
    await new Promise((res) => {
        setTimeout(() => { }, delay)
        res(1)
    })
}
